#!/usr/bin/env python3
# Author:liang futing
#@Time :2020/3/8 9:08
from django.contrib.auth import get_user_model
from django import forms
from django.core.exceptions import ValidationError,NON_FIELD_ERRORS
from django.forms import widgets
User=get_user_model()


class UserForm(forms.Form):
    user=forms.CharField(max_length=32, widget=widgets.TextInput(attrs={'class': 'form-control'},),
                         label='用户名',error_messages={'required':'该字段不能为空'})
    pwd=forms.CharField(max_length=32, widget=widgets.PasswordInput(attrs={'class': 'form-control'},),
                        label='密码')
    re_pwd=forms.CharField(max_length=32, widget=widgets.PasswordInput(attrs={'class': 'form-control'},),
                           label='重复密码')
    email=forms.EmailField(max_length=32, widget=widgets.EmailInput(attrs={'class': 'form-control'},),
                           label='邮箱')




    def clean(self):
        '''
        全局钩子函数检验
        验证两次密码是否一致
        '''
        pwd=self.cleaned_data.get("pwd")
        re_pwd = self.cleaned_data.get("re_pwd")
        if pwd and re_pwd:
            if pwd==re_pwd:
                return self.cleaned_data
            else:
                # 这个地方要抛出错误而不是用return 返回
                raise ValidationError("密码不一致")
        else:
            # 都为空时不处理直接返回
            return self.cleaned_data


    def clean_user(self):
        '''
        user 的钩子函数,验证用户名是否已经存在
        '''
        val1=self.cleaned_data.get('user')
        user=User.objects.filter(username=val1).first()
        if not user:
            #如果不存在用户，则说明是新用户
            return val1
        else:
            raise ValidationError("用户已存在")


